package com.lucenten.collect.gnss.handler.impl;

import cn.quevo.common.lang.NumberUtils;
import cn.quevo.common.lang.StringUtils;
import com.lucenten.collect.gnss.entity.GnssFile;
import com.lucenten.collect.gnss.enums.GnssFormat;
import com.lucenten.collect.gnss.handler.AbstractGnssHandler;
import com.lucenten.collect.gnss.handler.GnssHandler;
import com.lucenten.collect.gnss.handler.tools.GnssContext;
import com.lucenten.collect.gnss.handler.tools.TecpTeclTool;
import com.lucenten.collect.gnss.service.ObsErvationService;
import com.lucenten.collect.gnss.service.SatelliteStationService;

import java.nio.file.*;

/**
 * 第六步：文件合并
 */
public class TecpTeclGnssHandler extends AbstractGnssHandler implements GnssHandler {
    public TecpTeclGnssHandler(SatelliteStationService satelliteStationService, ObsErvationService obsErvationService) {
        super(satelliteStationService, obsErvationService);
    }

    @Override
    protected boolean doProcess(GnssFile gnssFile) {
        if (StringUtils.isEmpty(gnssFile.getDirFiles()) || gnssFile.getStation() == null
                || StringUtils.isBlank(gnssFile.getStation().getAntennaHeight(),-1) || StringUtils.isBlank(gnssFile.getStation().getLatitude(),-1)
                || StringUtils.isBlank(gnssFile.getStation().getLongitude(),-1)) {
            return true;
        }
        Path oPath = null;
        for (String fileName : gnssFile.getDirFiles()) {
            if (!fileName.endsWith("o")) {
                continue;
            }
            oPath = super.getUnZipPath(gnssFile, fileName);
            if (Files.notExists(oPath)) {
                continue;
            }
            this.tecpTecl(oPath, gnssFile);
        }
        return true;
    }

    // TODO 合并
    private void tecpTecl(Path file, GnssFile gnssFile) {
//        System.out.println("TECP合并");
        String fileName = file.getFileName().normalize().toString().toLowerCase();
        String days = NumberUtils.format(gnssFile.getDayOfYear(), "000");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String hour = GnssContext.TIME_CODE[gnssFile.getHoure()];
        if (!fileName.substring(4, 7).equalsIgnoreCase(days) || !fileName.substring(7, 8).equals(hour) || !fileName.endsWith(suffix)) {
            return;
        }
        new TecpTeclTool(satelliteStationService).merge(gnssFile, file, super.getDataFormatPath(GnssFormat.TECPTECL, gnssFile));
    }
}
